package com.elinkway.infinitemovies.ui.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.elinkway.infinitemovies.adapter.DownloadSlidePagerAdapter;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.download.ContainSizeManager;
import com.elinkway.infinitemovies.download.DownloadJob;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.ui.fragment.DownloadListFragment;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.Utils;
import com.le123.ysdq.R;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;


/**
 * 下载activity（从导航栏进入）
 */
public class DownloadActivity extends BaseActionBarActivity implements
        OnClickListener {

    public final static String TAG = "DownloadActivity";
    private ImageView mSelectBar;
    private int mImageWidth;
    private ViewPager mPager;
    private DownloadSlidePagerAdapter mPagerAdapter;
    public static int mCurrItem = 0;
    private int mOffset = 0;
    private TextView downloadTab;
    private TextView localVideoTab;
    private LinearLayout mDelLayout;
    private ArrayList<Fragment> fragmentsList;
    private DownloadListFragment mDownloadFragment;
    private TextView mTitle;
    private TextView mUserDeletecount;
    private int mDeletePopWindowHeight = 77;
    private PopupWindow mCheckAllPopWindow;
    private RelativeLayout mCheckTabLayout;
    private TextView mCheckTabText;
    private ImageView mLeftButton;
    private LinearLayout mBottomlayout;
    private TextView mConfirm_delete;
    public static ContainSizeManager mSizeManager;
    private String mTitleName;

    //网络变化广播接收
    private NetworkCheckReceiver mCheckReceiver;
    // 进入缓存页时间戳
    private long mOnCreateTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setActionBarActivityClassName(TAG);
        currentPageId = BigDataConstants.PGV_CURRENT_ID_DOWNLOAD;
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
        initActionBar();
        setContentView(R.layout.activity_download);
        mCurrItem = 0;
        mTitle = (TextView) findViewById(R.id.download_middle_title);
        mUserDeletecount = (TextView) findViewById(R.id.allselect);
        mUserDeletecount.setOnClickListener(this);
        mDelLayout = (LinearLayout) findViewById(R.id.delete_layout);
        downloadTab = (TextView) findViewById(R.id.download_tv);
        localVideoTab = (TextView) findViewById(R.id.localvideo_tv);
        downloadTab.setOnClickListener(clickListener);
        localVideoTab.setOnClickListener(clickListener);
        mLeftButton = (ImageView) findViewById(R.id.leftButtonLayout);
        mLeftButton.setOnClickListener(this);
        mBottomlayout = (LinearLayout) findViewById(R.id.bottomlayout);
        mConfirm_delete = (TextView) findViewById(R.id.confirm_delete);
        mConfirm_delete.setOnClickListener(this);
        initViewPager();

        mTitleName = (String) getIntent().getSerializableExtra(Utils.VIDEO_TITLE);
        initCheckTabPopWindow();
        mSizeManager = new ContainSizeManager(this);
        mSizeManager.ansynHandlerSdcardSize();
        mOnCreateTime = System.currentTimeMillis();
    }

    @Override
    protected void initActionBar(){
        super.initActionBar();
        mTitleTv.setText(R.string.download_manager);
        mRightFirstTv.setText("编辑");
        mRightFirstTv.setVisibility(View.GONE);
        mRightFirstTv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCurrItem == 0) {
                    ArrayList<DownloadJob> jobsList = MoviesApplication.getInstance().getDownloadManager().getProvider().getCompletedDownloads();
                    if (null != jobsList && jobsList.size() > 0) {
                        mDownloadFragment.updateDeleteView(mBottomlayout);
                        mUserDeletecount.setText(R.string.check_all);
                        mConfirm_delete.setText(R.string.delete_up);
                        mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
                    }

                } else if (mCurrItem == 1) {
//					mLocalVideoFragment.updateDeleteView();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        registerCheckNetwork();
        if (mCurrItem == 0) {
//			mDownloadFragment.updateDeleteIcon();
            updateDeleteIcon();
            //initTitleAndTab(0);
        } else if (mCurrItem == 1) {
            //mLocalVideoFragment.updateDeleteIcon(mDeleteIcon);
        }
    }

    private void initSliderImageView() {
        mSelectBar = (ImageView) findViewById(R.id.select_image);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mImageWidth = dm.widthPixels / 2;
        LayoutParams params = mSelectBar.getLayoutParams();
        params.width = mImageWidth;
        mSelectBar.setLayoutParams(params);
        Matrix matrix = new Matrix();
        matrix.postTranslate(0, 0);
        mSelectBar.setImageMatrix(matrix);
    }

    @Override
    protected void onPause() {
        super.onPause();
        long timeDiff = System.currentTimeMillis()-mOnCreateTime;
        reportUmengTimeDiff(timeDiff);
        MobclickAgent.onPause(this);
    }

    /**
     * 上报广告展示时间
     * 1. 0＜time≤300ms
     * 2. 300＜time≤600ms
     * 3. 600＜time≤700ms
     * 4. 700＜time≤900ms
     * 5. time＞900ms
     * @param timeDiff 时间差
     */
    private void reportUmengTimeDiff(long timeDiff) {
        String time = "0";
        if ( 0 < timeDiff && timeDiff <= 300) {
            time = "1";
        } else if (300 < timeDiff && timeDiff <= 600) {
            time = "2";
        } else if (600 < timeDiff && timeDiff <= 700) {
            time = "3";
        } else if (700 < timeDiff && timeDiff <= 900) {
            time = "4";
        } else if (timeDiff > 900) {
            time = "5";
        }
        UmengEventPoster.postDownLoadTime(time);
    }

    private void initViewPager() {
        mPager = (ViewPager) findViewById(R.id.vpager);
        fragmentsList = new ArrayList<Fragment>(2);
        mDownloadFragment = new DownloadListFragment();
//		mLocalVideoFragment = new LocalVideoListFragment();
        fragmentsList.add(mDownloadFragment);
//		fragmentsList.add(mLocalVideoFragment);
        mPagerAdapter = new DownloadSlidePagerAdapter(
                getSupportFragmentManager(), fragmentsList);
        setPagerCurItem(mCurrItem);
        mPager.setAdapter(mPagerAdapter);
        mPager.setOnPageChangeListener(new PageChangeListener());
    }

    private void setPagerCurItem(int index) {
        initTitleAndTab(index);
        mCurrItem = index;
        mPager.setCurrentItem(index);
    }

    private void initTitleAndTab(int index) {
        switch (index) {
            case 0:
                updateDeleteIcon();
                downloadTab.setTextColor(getResources().getColor(R.color.black));
                localVideoTab.setTextColor(this.getResources().getColor(
                        R.color.download_manager_textcolor));
                if (mDownloadFragment.adapter != null && mDownloadFragment.adapter.isDeleteState()
                        && mDownloadFragment.adapter.getCount() > 0) {
                    mDownloadFragment.handleBackOnDelete();
                }
                break;
            case 1:
                localVideoTab.setTextColor(getResources().getColor(R.color.black));
                downloadTab.setTextColor(this.getResources().getColor(
                        R.color.download_manager_textcolor));
                break;
            default:
                break;
        }
    }

    private class PageChangeListener implements OnPageChangeListener {

        int one = mOffset * 2 + mImageWidth;

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageSelected(int index) {

            Animation animation = new TranslateAnimation(one * mCurrItem, one
                    * index, 0, 0);
            mCurrItem = index;
            setPagerCurItem(mCurrItem);
            animation.setFillAfter(true);// True:图片停在动画结束位置
            animation.setDuration(300);
            if (null != mSelectBar) {
                mSelectBar.startAnimation(animation);
            }
        }
    }

    OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.download_tv:
//				setPagerCurItem(0);
                    break;
                case R.id.localvideo_tv:
                    setPagerCurItem(1);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.delete_layout:
                if (mCurrItem == 0) {
                    ArrayList<DownloadJob> jobsList = MoviesApplication.getInstance().getDownloadManager().getProvider().getCompletedDownloads();
                    if (null != jobsList && jobsList.size() > 0) {
                        mDownloadFragment.updateDeleteView(mBottomlayout);
                        mUserDeletecount.setText(R.string.check_all);
                        mConfirm_delete.setText(R.string.delete_up);
                        mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
                    }

                } else if (mCurrItem == 1) {
                }
                break;
            case R.id.confirm_delete:
                if (mCurrItem == 0) {
                    mDownloadFragment.updateConfirmDeleteView(mBottomlayout);
                } else if (mCurrItem == 1) {

                }
                break;

            case R.id.allselect:
                if (mCurrItem == 0) {
                    checkUserSelectAll();
                    mDownloadFragment.selectDownloadVideo();
                } else if (mCurrItem == 1) {
                }
                break;
            case R.id.leftButtonLayout:
                onClickBackButton();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            onClickBackButton();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void onClickBackButton() {
        // 如果当前是删除编辑状态则先恢复至初始状态
        if (mCurrItem == 0) {
            if (mDownloadFragment.adapter != null && mDownloadFragment.adapter.isDeleteState()
                    && mDownloadFragment.adapter.getCount() > 0) {
                mRightFirstTv.setText(getResources().getString(R.string.edit));
                mBottomlayout.setVisibility(View.GONE);
                mDownloadFragment.handleBackOnDelete();
            }
        }
        // 如果当前是本地视频删除编辑状态，用户点击back键首先恢复到初始状态
        else if (mCurrItem == 1) {
        }
        finish();
    }

    private void setCheckTabText(boolean isAll) {
        if (isAll) {
            mUserDeletecount.setText(R.string.check_all);
        } else {
            mUserDeletecount.setText(R.string.deselect_all);

        }
    }

    public void restoreDeleteView() {
        mTitle.setVisibility(View.VISIBLE);
        mConfirm_delete.setText(R.string.delete_up);
        mConfirm_delete.setTextColor(getResources().getColor(R.color.all_select));
        if (mDownloadFragment.adapter != null && mDownloadFragment.adapter.getCount() > 0) {
        }
    }

    public void deleteView(int deleteNum) {
        String content = getString(R.string.delete_up) + "(" + deleteNum
                + ")";
        mConfirm_delete.setText(content);
        mConfirm_delete.setTextColor(getResources().getColor(R.color.red_f9362a));
    }

    private void checkUserSelectAll() {
        if (null != mDownloadFragment.adapter) {
            boolean isAll = mDownloadFragment.adapter.deletedNum == mDownloadFragment
                    .getRemainNum() ? true : false;
            setCheckTabText(isAll);
        }
    }

    private void initCheckTabPopWindow() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View mPopWindowView = inflater
                .inflate(R.layout.user_checkall_tab, null);
        if (null != mPopWindowView) {
            mCheckAllPopWindow = new PopupWindow(mPopWindowView, 232,
                    mDeletePopWindowHeight);
            mCheckAllPopWindow.setFocusable(true);
            mCheckAllPopWindow.setBackgroundDrawable(new BitmapDrawable());
            initPopWindowComponent(mPopWindowView);
        }
    }

    private void initPopWindowComponent(View view) {
        mCheckTabLayout = (RelativeLayout) view
                .findViewById(R.id.check_tab_layout);
        mCheckTabText = (TextView) view.findViewById(R.id.user_checkall_tv);
        mCheckTabLayout.setOnClickListener(this);
    }

    ;

    private void dismissPopWindow() {
        if (mCheckAllPopWindow.isShowing()) {
            mCheckAllPopWindow.dismiss();
        }
    }


    /**
     * qinguoli
     * 注册监听手机网络广播 接收
     */
    protected void registerCheckNetwork() {
        mCheckReceiver = new NetworkCheckReceiver();
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(PlayerUtils.CONNECTIVTY_CHANGE);
        this.registerReceiver(mCheckReceiver, intentfilter);
    }

    /**
     * qinguoli
     * 取消对网络变化的监听*
     */
    protected void unregisterCheckNetwork() {
        if (mCheckReceiver != null) {
            try {
                this.unregisterReceiver(mCheckReceiver);
            } catch (IllegalArgumentException e) {
                if (e.getMessage().contains("Receiver not registered")) {
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!ignore incorrect unregisterCheckNetwork!!!!!!!!!!!!!!!!!");
                    // Ignore this exception. This is exactly what is desired
                } else {
                    // unexpected, re-throw
                    throw e;
                }
            }
        }
    }

    /**
     * qinguoli
     * 网络广播监听*
     */
    class NetworkCheckReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {

                //读取保存的之前网络状态
                SharedPreferences priorNetState = getSharedPreferences("priornetstate",
                        Activity.MODE_PRIVATE);

                int priorNetType = priorNetState.getInt("netstate", 2);

                int nowNetType = NetWorkTypeUtils.checkNet(intent, priorNetType);


                SharedPreferences.Editor editor = priorNetState.edit();

                editor.putInt("netstate", nowNetType);
                editor.commit();

            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterCheckNetwork();
    }

    /**
     * @param isShowFilterButton 是否显示
     */
    public void setFilterButtonState(boolean isShowFilterButton) {
        if(isShowFilterButton){
            mRightFirstTv.setVisibility(View.VISIBLE);
        }else{
            mRightFirstTv.setVisibility(View.GONE);
        }

    }

    private void updateDeleteIcon() {
        if (MoviesApplication.getInstance().getDownloadManager().getCompletedDownloads().size() > 0) {
            setFilterButtonState(true);
        } else {
            setFilterButtonState(false);
        }
    }

    @Override
    public void dealWithUmeng() {
    }

    @Override
    public void dealWithVisitUmeng() {

    }
}
